<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽</title>
    <style>
        #drag{
            width: 150px;
            height: 150px;
            background-color: red;
            position: absolute;
            left:0;
            top:0;
        }
    </style>
</head>
<body>
    <div id="drag"></div>
    <script>
        let drag = document.getElementById("drag");
        drag.onmousedown = function(e){
            let x = e.x - parseInt(drag.style.left || 0);
            let y = e.y - parseInt(drag.style.top || 0);
            document.onmousemove = function(e){
                let left = e.x - x;
                let top = e.y - y;
                drag.style.left = left + "px";
                drag.style.top = top + "px";
            }
            document.onmouseup = function(){
                document.onmousemove = null;
                document.onmouseup = null;
            }
        }
    </script>
</body>
</html>